package cn.com.zsc.schedule;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;

public class InitSchedule extends HttpServlet{
	/**
	 * Constructor of the object.
	 */
	public InitSchedule() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just pf" string in log
		// Put your code here
	}
	
	/**
	 * 清除任务
	 * @param inScheduler
	 * 任务队列
	 * @throws Exception
	 */
	public void cleanUp(Scheduler inScheduler) throws Exception {
        // unschedule jobs
        String[] groups = inScheduler.getTriggerGroupNames();
        for (int i = 0; i < groups.length; i++) {
            String[] names = inScheduler.getTriggerNames(groups[i]);
            for (int j = 0; j < names.length; j++) {
                inScheduler.unscheduleJob(names[j], groups[i]);
            }
        }

        // delete jobs
        groups = inScheduler.getJobGroupNames();
        for (int i = 0; i < groups.length; i++) {
            String[] names = inScheduler.getJobNames(groups[i]);
            for (int j = 0; j < names.length; j++) {
                inScheduler.deleteJob(names[j], groups[i]);
            }
        }
    }
	
	
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		//获得任务实例
		try {
			SchedulerUtils.scheduler=StdSchedulerFactory.getDefaultScheduler();
			SchedulerUtils.scheduler.start();
		} catch (SchedulerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//清除所有任务
		try {
			cleanUp(SchedulerUtils.scheduler);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		InitTask ist=new InitTask();
		ist.addADTask(SchedulerUtils.scheduler);
	}
}
